import { Evaluator } from "rollup-web";
import { FileStore } from "../interface";

export type LoadFile = (string: string) => Promise<string>;

type Config = { target?: string; compiler?: { url?: string } };

export class CompilerManager {
    /** Compiler 线程的代码，通过这个代码判断是否为同一个 */
    code = "";

    config!: Config;
    public fileStore: FileStore;
    public getCompilerCode() {
        return this.fileStore.getFileString("/.web.compiler.js");
    }
    constructor(props: { fileStore: FileStore }) {
        Object.assign(this, props);
    }
    /* 构建 json 配置文件 */
    async loadConfig(setting?: Partial<Config>) {
        this.config = {};
    }
    private evaluator = new Evaluator();
    async createPort() {
        const code = await this.getCompilerCode();
        const isSame = this.checkSameCode(code);
        if (isSame) {
            return this.evaluator.createCompilerPort();
        } else {
            this.code = code;
            return this.recreateCompilerPort(code);
        }
    }
    checkSameCode(code: string) {
        return this.code !== "" && code === this.code;
    }
    /* 重置 Compiler */
    async recreateCompilerPort(code: string): Promise<MessagePort> {
        const file = new File([code], "index.js", {
            type: "text/javascript",
        });
        const url = URL.createObjectURL(file);
        this.evaluator.Compiler?.destroy();
        await this.evaluator.useWorker(url);
        return this.evaluator.createCompilerPort();
    }

    destroy() {
        this.evaluator.Compiler?.destroy();
    }
}
